package com.ark.frigate.zookeeper.state;

import javax.annotation.Resource;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author ZengWeiLong
 * @Description Copy Right Beyonca
 * @Date 2022/3/25 20:16
 * @Version 1.0
 */
@RestController
@RequestMapping("/statemachine")
public class StateMachineController {
    @Resource
    private OrderStateMachineBuilder orderStateMachineBuilder;

    @Resource
    private BeanFactory beanFactory;

    @GetMapping("/testOrderState")
    public void testOrderState(String orderId) throws Exception {
        StateMachine<OrderStates, OrderEvents> stateMachine = orderStateMachineBuilder.build(beanFactory,
                OrderStates.UNPAID);
        System.out.println(stateMachine.getId());
        //用message传递数据
        Order order = new Order(orderId, "547568678", "广东省深圳市", "13435465465", "RECEIVE");
        // 创建流程
        stateMachine.start();
        // 触发PAY事件
        Message<OrderEvents> message =
                MessageBuilder.withPayload(OrderEvents.PAY).setHeader("order", order).setHeader("otherObj",
                        "otherObjValue").build();
        stateMachine.sendEvent(message);
        // 触发RECEIVE事件
        Message<OrderEvents> message2 = MessageBuilder.withPayload(OrderEvents.RECEIVE).setHeader("order", order)
                .setHeader("otherObj", "otherObjValue").build();
        //        stateMachine.sendEvent(OrderEvents.RECEIVE);
        stateMachine.sendEvent(message2);
        // 获取最终状态
        System.out.println("最终状态：" + stateMachine.getState().getId());
    }
}